package cate.game.pvp.eliterace.data;

import cate.game.framework.common.compress.CompressedContent;
import cate.game.framework.common.compress.PlaySideCompressHelper;
import cate.game.play.part.PlaySide;
import cate.game.pvp.pointrace.data.PointRacePs;
import com.google.common.collect.Lists;
import easy.java.practice.errorcode.EcResult;
import lombok.Data;
import lombok.ToString;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

import java.io.IOException;
import java.util.LinkedList;

import static cate.game.pvp.eliterace.data.EliteRaceOpponent.ofCopy;

@ToString
@Data
@Document(collection = "elite-race-ps")
public class EliteRacePs {

    public static final String INDEX_NAME = "INDEX";

    @Id
    private String uid;
    private EliteRaceOpponent opponent;

    private LinkedList<CompressedContent> cpsList;

    public static EliteRacePs compress(PlaySide ps, long points) throws IOException {
        EliteRacePs eps = new EliteRacePs();
        eps.setUid(ps.snapshot.uid);
        eps.setOpponent(ofCopy(ps.snapshot, points));
        LinkedList<CompressedContent> cpsList = Lists.newLinkedList();
        cpsList.add(PlaySideCompressHelper.compress(ps));
        eps.setCpsList(cpsList);
        return eps;
    }

    public static EcResult<EliteRacePs> compressEc(PlaySide playSide, long points) {
        EcResult<EliteRacePs> r = new EcResult<>();
        try {
            r.data = compress(playSide, points);
        } catch (Throwable cause) {
            return r.fail(cause);
        }
        return r.success();
    }

    public static EliteRacePs of(PointRacePs pps, int rank) {
        EliteRacePs eps = new EliteRacePs();
        eps.setUid(pps.getUid());
        eps.setOpponent(EliteRaceOpponent.of(pps.getOpponent(), rank));
        eps.setCpsList(Lists.newLinkedList());
        eps.getCpsList().add(pps.getCps());
        return eps;
    }

    public String getIndexKey() {
        return getUid();
    }
}
